# -*- coding: utf8 -*-

from project.mysql.table import Table

class TableOption( Table ):

    _table_name = "option"

    def create( self ):
        cur = self.getCursor()

        # Create table
        cur.execute(
            "CREATE TABLE IF NOT EXISTS `%s` (" % self._table_name+
#            "`id` SMALLINT UNSIGNED AUTO_INCREMENT PRIMARY KEY, "+
            "`name` VARCHAR(255) NOT NULL PRIMARY KEY, "+
            "`value` TEXT "+
            ") ENGINE %s" % self.getEngine()
        )
#        try:
#            cur.execute(
#               "ALTER TABLE `%s` ADD INDEX `name` (`name`)" % self._table_name
#            )
#        except:
#            pass
        cur.close()
        return


    def save( self, name, value ):
        """
        @return: id
        @rtype: int
        """
        cur = self.getCursor()

        cur.execute("SELECT * FROM `%s` " % self._table_name+
                    "WHERE `name`=%s", ( name, ) )
        item = cur.fetchone()

        if not item:
            rows = cur.execute("INSERT INTO `%s` " % self._table_name+
                               " (`name`, `value`) VALUES (%s, %s)", ( name, value, ))
        else:
            rows = cur.execute("UPDATE `%s` " % self._table_name+
                        "SET `value`=%(value)s WHERE `name`=%(name)s", {
                "name":name,
                "value":value
            })
        cur.close()
        self.getConnection().commit()
        return rows

    def get( self, name ):
        cur = self.getCursor()
        cur.execute("SELECT `value` FROM `%s` " % self._table_name+
                    "WHERE `name`=%s", (
            name )
        )
        item = cur.fetchone()
        if item:
            item = item["value"]
        cur.close()
        return item


    def options( self ):
        cur = self.getCursor()
        cur.execute("SELECT * FROM `%s`" % self._table_name)
        items = cur.fetchall()
        cur.close()
        opts = {}
        for item in items:
            opts[ item["name"] ] = item["value"]
        return opts

    pass
